package com.umeox.watch.prayertime.ui

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.os.Bundle
import android.provider.Settings
import android.text.format.DateFormat
import android.view.View
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.view.animation.RotateAnimation
import android.widget.ImageButton
import android.widget.RelativeLayout
import com.umeox.moto.common.log.Logger
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity
import com.umeox.moto.watch.themes.util.CountDownTimer
import com.umeox.moto.watch.themes.widget.ImageView
import com.umeox.moto.watch.themes.widget.TextView
import com.umeox.watch.moto.dataservice.constants.Constants
import com.umeox.watch.prayertime.R
import com.umeox.watch.prayertime.base.BaseApp
import com.umeox.watch.prayertime.bean.PrayerTimeInfo
import com.umeox.watch.prayertime.utils.PrayerTimesCoordinator
import com.umeox.watch.prayertime.utils.Utils
import java.io.Serializable
import java.util.*

class MainActivity : ThemeAppCompatActivity() {

    private var mDownTimer: CountDownTimer? = null
    private var mLocationDownTimer: CountDownTimer? = null
    private lateinit var mNoDataView: View
    private lateinit var mPrayerTimeView: View
    private lateinit var mPrayerTimeName: TextView
    private lateinit var mPrayerTime: TextView
    private lateinit var mPrayerTimeAmPm: TextView
    private lateinit var mPrayerTimeTip: TextView
    private lateinit var mPrayerTimeCount: TextView
    private lateinit var mLocationRl: RelativeLayout
    private lateinit var mRefreshIcon: ImageView
    private lateinit var prayerTimesCoordinator: PrayerTimesCoordinator

    private var prayerTimeList: MutableList<PrayerTimeInfo>? = null

    private var rotate: RotateAnimation? = null

    private var is24HourFormat: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        is24HourFormat = DateFormat.is24HourFormat(this)
        prayerTimesCoordinator = PrayerTimesCoordinator()
        //获取本地经纬度
        val lat: String? = Settings.Global.getString(contentResolver, "LAT")
        val long: String? = Settings.Global.getString(contentResolver, "LONG")
        Logger.e("lat=$lat,long=$long")
        if ((!lat.isNullOrEmpty() && lat != "-999") && (!long.isNullOrEmpty() && long != "-999")) {
            calcPrayerTime(lat.toDouble(), long.toDouble())
        }
        Logger.e("$prayerTimeList")
        initView()
        initData()
    }

    private fun initView() {
        mNoDataView = findViewById(R.id.ll_no_data)
        mPrayerTimeView = findViewById(R.id.ll_prayer_time)
        mPrayerTimeName = findViewById(R.id.tv_prayer_time_name)
        mPrayerTime = findViewById(R.id.tv_prayer_time)
        mPrayerTimeTip = findViewById(R.id.tv_time_tip)
        mPrayerTimeCount = findViewById(R.id.tv_time_count)
        mPrayerTimeAmPm = findViewById(R.id.tv_prayer_time_am_pm)
        mLocationRl = findViewById(R.id.rl_refresh)
        mRefreshIcon = findViewById(R.id.iv_refresh)


        registerLocationReceiver()

        findViewById<ImageView>(R.id.ib_prayer_time_list).setOnClickListener {

            val intent = Intent(this@MainActivity, PrayerTimeListActivity::class.java)
            startActivity(intent)
        }

        mLocationRl.setOnClickListener {
            mLocationRl.isClickable = false
            //开始定位 图标动画 计时
            sendBroadcast(Intent("com.wherecom.intent.action.PRAYER_LOCATION"))

            searchAnimation()
            if (rotate != null) {
                mRefreshIcon.startAnimation(rotate)
            }

            mLocationDownTimer = LocationTimeCountDownTimer(45 * 1000, 1000)
            mLocationDownTimer?.start()
        }

    }

    private fun initData() {
        if (prayerTimeList != null) {
            mNoDataView.visibility = View.GONE
            mPrayerTimeView.visibility = View.VISIBLE
            //根据当前时间
            val currentTimeMillis = System.currentTimeMillis()
            val nextPrayerTimeIndex: Int = binarySearchLeft(prayerTimeList!!, currentTimeMillis)
            if (nextPrayerTimeIndex == (prayerTimeList?.size?.minus(1))) { //计算得出的下一次时间是午夜时间
                val midnightPrayerTimeInfo = prayerTimeList!![nextPrayerTimeIndex] //取出午夜时间信息
                val needShowPrayerTimeInfo = prayerTimeList!![nextPrayerTimeIndex - 1] // 取出Isha

                mPrayerTimeName.text = needShowPrayerTimeInfo.prayerTimeName
                if (is24HourFormat) {
                    mPrayerTime.text = Utils.to24HourFormat(
                        needShowPrayerTimeInfo.prayerTime,
                        Locale.getDefault()
                    )
                    mPrayerTimeAmPm.visibility = View.GONE
                } else {
                    mPrayerTime.text = Utils.to12HourFormat(
                        needShowPrayerTimeInfo.prayerTime,
                        Locale.getDefault()
                    )
                    mPrayerTimeAmPm.visibility = View.VISIBLE
                    mPrayerTimeAmPm.text = needShowPrayerTimeInfo.timeType
                }
                mPrayerTimeTip.text = getString(R.string.elapsed_time)
                mPrayerTimeCount.setTextColor(Color.parseColor("#30EB75"))
                mDownTimer?.cancel()
                mDownTimer = TimeCountDownTimer(
                    midnightPrayerTimeInfo.timestamp - currentTimeMillis,
                    1000,
                    1,
                    currentTimeMillis - needShowPrayerTimeInfo.timestamp
                )
                mDownTimer?.start()

            } else if (nextPrayerTimeIndex == -1) {
                val needShowPrayerTimeInfo = prayerTimeList!![0] // 取出Fajr
                mPrayerTimeName.text = needShowPrayerTimeInfo.prayerTimeName
                if (is24HourFormat) {
                    mPrayerTime.text = Utils.to24HourFormat(
                        needShowPrayerTimeInfo.prayerTime,
                        Locale.getDefault()
                    )
                    mPrayerTimeAmPm.visibility = View.GONE
                } else {
                    mPrayerTime.text = Utils.to12HourFormat(
                        needShowPrayerTimeInfo.prayerTime,
                        Locale.getDefault()
                    )
                    mPrayerTimeAmPm.visibility = View.VISIBLE
                    mPrayerTimeAmPm.text = needShowPrayerTimeInfo.timeType
                }
                mPrayerTimeTip.text = getString(R.string.remaining_time)
                mPrayerTimeCount.setTextColor(Color.parseColor("#FDDDA6"))
                mDownTimer?.cancel()
                mDownTimer = TimeCountDownTimer(
                    needShowPrayerTimeInfo.timestamp - currentTimeMillis,
                    1000,
                    0,
                    (currentTimeMillis - needShowPrayerTimeInfo.timestamp)
                )
                mDownTimer?.start()
            } else {
                val nextPrayerTimeInfo = prayerTimeList!![nextPrayerTimeIndex]
                Logger.e("$nextPrayerTimeInfo")
                mPrayerTimeName.text = nextPrayerTimeInfo.prayerTimeName
                if (is24HourFormat) {
                    mPrayerTime.text = Utils.to24HourFormat(
                        nextPrayerTimeInfo.prayerTime,
                        Locale.getDefault()
                    )
                    mPrayerTimeAmPm.visibility = View.GONE
                } else {
                    mPrayerTime.text = Utils.to12HourFormat(
                        nextPrayerTimeInfo.prayerTime,
                        Locale.getDefault()
                    )
                    mPrayerTimeAmPm.visibility = View.VISIBLE
                    mPrayerTimeAmPm.text = nextPrayerTimeInfo.timeType
                }


                mPrayerTimeTip.text = getString(R.string.remaining_time)
                mPrayerTimeCount.setTextColor(Color.parseColor("#FDDDA6"))
                mDownTimer?.cancel()
                mDownTimer =
                    TimeCountDownTimer(
                        nextPrayerTimeInfo.timestamp - currentTimeMillis,
                        1000,
                        0,
                        0
                    )
                mDownTimer?.start()
            }
        } else {
            mNoDataView.visibility = View.VISIBLE
            mPrayerTimeView.visibility = View.GONE
        }
    }

    //找到>=target最左的位置
    private fun binarySearchLeft(arr: MutableList<PrayerTimeInfo>, target: Long): Int {
        var left = 0
        var right = arr.size - 1
        var result = -1
        while (left <= right) {
            val middle = left + (right - left shr 1)
            if (arr[middle].timestamp >= target) {
                result = middle
                right = middle - 1
            } else {
                left = middle + 1
            }
        }
        return result
    }

    inner class TimeCountDownTimer(
        private val millisInFuture: Long,
        countDownInterval: Long,
        private val type: Int,
        private val offsetTime: Long
    ) :
        CountDownTimer(millisInFuture, countDownInterval) {

        override fun onTick(millisUntilFinished: Long) {
            if (type == 0) {
                val secs = millisUntilFinished / 1000
//                if (secs >= 3600) {
                    mPrayerTimeCount.text =
                        String.format(
                            Locale.getDefault(), "%02d:%02d:%02d", secs / 3600, secs % 3600 / 60,
                            secs % 60
                        )
//                } else {
//                    mPrayerTimeCount.text =
//                        String.format(
//                            Locale.ENGLISH, "%02d:%02d", secs % 3600 / 60,
//                            secs % 60
//                        )
//                }
            } else {
                val secs = (millisInFuture - millisUntilFinished + offsetTime) / 1000
//                if (secs >= 3600) {
                    mPrayerTimeCount.text =
                        String.format(
                            Locale.getDefault(), "%02d:%02d:%02d", secs / 3600, secs % 3600 / 60,
                            secs % 60
                        )
//                } else {
//                    mPrayerTimeCount.text =
//                        String.format(
//                            Locale.ENGLISH, "%02d:%02d", secs % 3600 / 60,
//                            secs % 60
//                        )
//                }
            }
        }

        override fun onFinish() {
            //停在界面倒计时或者正计时走完 更新下一次显示的UI
            initData()
        }

    }


    inner class LocationTimeCountDownTimer(
        private val millisInFuture: Long,
        countDownInterval: Long
    ) :
        CountDownTimer(millisInFuture, countDownInterval) {

        private var costTime = 0 //秒


        override fun onTick(millisUntilFinished: Long) {
            costTime = ((millisInFuture - millisUntilFinished) / 1000).toInt()
            if (costTime == 40) {
                //GPS定位超时了，需要向服务器拿数据
                val intent = Intent("com.wherecom.intent.action.GET_DEVICE_LAST_LOCATION")
                sendBroadcast(intent)
            }
            Logger.e("已定位耗时:$costTime")
        }

        override fun onFinish() {
            if (rotate != null && rotate!!.hasStarted()) {
                rotate!!.cancel()
            }
            mLocationRl.isClickable = true
        }

    }

    private val mLocationReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            Logger.e("action=$action")
            if (action == Constants.ACTION_LOCATION_SUCCESS) {
                if (rotate != null && rotate!!.hasStarted()) {
                    rotate!!.cancel()
                }
                mLocationRl.isClickable = true
                mLocationDownTimer?.cancel()

                val lat = intent.getStringExtra("LAT")
                val long = intent.getStringExtra("LONG")
                Logger.e("lat=$lat,long=$long")
                if (lat != "-999" && long != "-999") {
                    Settings.Global.putString(contentResolver, "LAT", lat)
                    Settings.Global.putString(contentResolver, "LONG", long)

                    calcPrayerTime(lat?.toDouble()!!, long?.toDouble()!!)
                    initData()
                    BaseApp.getInstance().schedulePrayerTimeAlarm()
                }
            } else if (action == Constants.ACTION_UPDATED_PRAYER_TIME) {  //祈祷设置发生改变，重新计算

                val lat = Settings.Global.getString(contentResolver, "LAT")
                val long = Settings.Global.getString(contentResolver, "LONG")

                Logger.e("lat=$lat,long=$long")
                if (lat != "-999" && long != "-999") {
                    calcPrayerTime(lat.toDouble(), long.toDouble())
                    initData()
                    BaseApp.getInstance().schedulePrayerTimeAlarm()
                }
            } else if (action == Constants.ACTION_UPDATED_PRAYER_ALARMLIST) {
                BaseApp.getInstance().schedulePrayerTimeAlarm()
            }
        }
    }

    private fun calcPrayerTime(lat: Double, long: Double) {
        prayerTimesCoordinator.updateParameters(is24HourFormat)
        val timeZone: TimeZone = TimeZone.getDefault()
        val time = timeZone.rawOffset //获取时差，返回值毫秒
        prayerTimeList = prayerTimesCoordinator.getPrayerTimeData(
            lat,
            long,
            (time / 1000 / 60 / 60).toDouble()
        )
        Logger.e("$prayerTimeList")
    }

    private fun registerLocationReceiver() {
        val mFilter = IntentFilter()
        mFilter.addAction(Constants.ACTION_LOCATION_SUCCESS)
        mFilter.addAction(Constants.ACTION_UPDATED_PRAYER_TIME)
        mFilter.addAction(Constants.ACTION_UPDATED_PRAYER_ALARMLIST)
        registerReceiver(mLocationReceiver, mFilter)
    }


    override fun onDestroy() {
        super.onDestroy()
        mDownTimer?.cancel()
        mLocationDownTimer?.cancel()

        try {
            unregisterReceiver(mLocationReceiver)
        } catch (ignored: Exception) {

        }
    }

    private fun searchAnimation() {
        if (rotate == null) {
            rotate = RotateAnimation(
                0f,
                360f,
                Animation.RELATIVE_TO_SELF,
                0.5f,
                Animation.RELATIVE_TO_SELF,
                0.5f
            )
            val lin = LinearInterpolator()
            rotate?.interpolator = lin
            rotate?.duration = 800 //设置动画持续时间
            rotate?.repeatCount = -1 //设置重复次数
            rotate?.fillAfter = false //动画执行完后是否停留在执行完的状态
        }
    }

}

